package com.bestom.producetest.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bestom.producetest.R;
import com.bestom.producetest.utils.AppUtil;
import com.bestom.producetest.utils.ProperTiesUtils;

import static com.bestom.producetest.base.App.configfilename;

public class SensorActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "SensorActivity";
    private Activity mActivity;
    private SensorManager mSensorManager;
    private Sensor mGSensor, mLSensor;

    private GSensorListener mGSensorListener;
    private LightSensorListener mLightSensorListener;

    LinearLayout GSensor_layout, LSensor_layout;
    TextView tv_x, tv_y, tv_z, tv_g;

    private class LightSensorListener implements SensorEventListener {

        private float lux; // light intensity

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            // Get light intensity
            lux = event.values[0];
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_g.setText("" + lux);
                }
            });
        }

    }

    /**
     * Step 4: Implement the SensorListener interface
     */
    private class GSensorListener implements SensorEventListener {

        /**
         * Calling back interface where sensor accuracy changes
         */
        @Override
        public final void onAccuracyChanged(Sensor sensor, final int accuracy) {
            //TODO Do some operations when the sensor accuracy is changed. Accuracy is the current sensor accuracy
        }

        /**
         * Callback interface when sensor event values change:
         * The frequency with which this method is executed is related to the frequency with which the sensor is registered
         */
        @Override
        public final void onSensorChanged(SensorEvent event) {
            // Most sensors will return the event values of x,y, and x along the three axes, and the meaning of the values varies from sensor to sensor
            final float x = event.values[0];
            final float y = event.values[1];
            final float z = event.values[2];
            isCan = true;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_x.setText("" + x);
                    tv_y.setText("" + y);
                    tv_z.setText("" + z);
                }
            });
        }
    }

    @Override
    public final void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        // Hide the bottom navigation bar
        if (AppUtil.hasNavBar(this)) {
            AppUtil.hideBottomUIMenu(this);
        }
        setContentView(R.layout.activity_sensor);

        initView();
        //Step 1: Get the SensorManager instance object through GetSystemService
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //Step 2: Get the desired sensor object through the SensorManager instance object: The parameter determines which sensor to get
        if (mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
            // Success! There's a magnetometer.
            mGSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        } else {
            // Failure! No magnetometer.
            Log.e(TAG, "Failure! No support Sensor.TYPE_ACCELEROMETER.");
        }

        if (mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) != null) {
            // Success! There's a magnetometer.
            mLSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        } else {
            // Failure! No magnetometer.
            Log.e(TAG, "Failure! No support Sensor.TYPE_LIGHT.");
        }

    }

    /**
     * boolean isCan
     * In order not to set system properties repeatedly
     */
    private boolean isCan;

    private void initView() {
        GSensor_layout = findViewById(R.id.Gsensor_test);
        tv_x = findViewById(R.id.tv_X);
        tv_y = findViewById(R.id.tv_Y);
        tv_z = findViewById(R.id.tv_Z);
        LSensor_layout = findViewById(R.id.LightSeneor_test);
        tv_g = findViewById(R.id.tv_g);
        GSensor_layout.setVisibility(Integer.valueOf(ProperTiesUtils.getProperties(mActivity, configfilename, "GSensorTest")) == 1 ? View.VISIBLE : View.GONE);
        LSensor_layout.setVisibility(Integer.valueOf(ProperTiesUtils.getProperties(mActivity, configfilename, "LightSensorTest")) == 1 ? View.VISIBLE : View.GONE);

        findViewById(R.id.close_btn).setOnClickListener(this);
        findViewById(R.id.default_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCan) {
                    new AlertDialog.Builder(SensorActivity.this)
                            .setTitle(R.string.sensor_management)
                            .setMessage(R.string.ban_sensor)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // Disable the sensors
                                    ProperTiesUtils.setProp("persist.sys.disablesensors", "true");
                                    // After setting system properties, you must restart the current page
                                    reStartActivity();
                                }
                            })
                            .setNegativeButton(R.string.no, null)
                            .show();
                } else {
                    Toast.makeText(getApplicationContext(), R.string.sensor_disenable, Toast.LENGTH_SHORT).show();
                }
            }
        });
        findViewById(R.id.default_open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (isCan) {
                    Toast.makeText(getApplicationContext(), R.string.sensor_enable, Toast.LENGTH_SHORT).show();
                } else {
                    new AlertDialog.Builder(SensorActivity.this)
                            .setTitle(R.string.sensor_management)
                            .setMessage(R.string.enable_sensor)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // Make the sensors available
                                    ProperTiesUtils.setProp("persist.sys.disablesensors", "false");
                                    // After setting system properties, you must restart the current page
                                    reStartActivity();
                                }
                            })
                            .setNegativeButton(R.string.no, null)
                            .show();
                }
            }
        });
    }


    /**
     * Step 3: Register the sensor when the focus is acquired and have this class implement the SensorListener interface
     */
    @Override
    protected void onResume() {
        super.onResume();
        /**
         * MSensorManager. RegisterListener parameters:
         * First parameter: an instance object of the SensoReventListener interface
         * Second parameter: the sensor instance that needs to be registered
         * The third parameter: sensor gets sensor event value frequency:
         *     SensorManager.SENSOR_DELAY_FASTEST = 0：Update interval corresponding to 0 microseconds, the fastest, 1 microsecond = 1% 1000000 seconds
         *     SensorManager.SENSOR_DELAY_GAME = 1：This corresponds to a 20,000 microsecond update interval, which is often used in games
         *     SensorManager.SENSOR_DELAY_UI = 2：The update interval corresponds to 60,000 microseconds
         *     SensorManager.SENSOR_DELAY_NORMAL = 3：The update interval corresponds to 200000 microseconds
         *     When you type the custom int value x: the update interval corresponding to x microseconds
         */
        if (mGSensor != null) {
            mGSensorListener = new GSensorListener();
            mSensorManager.registerListener(mGSensorListener, mGSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }

        if (mLSensor != null) {
            mLightSensorListener = new LightSensorListener();
            mSensorManager.registerListener(mLightSensorListener, mLSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    /**
     * Step 5: Log off the sensor when it loses focus
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (mGSensorListener != null)
            mSensorManager.unregisterListener(mGSensorListener);
        if (mLightSensorListener != null)
            mSensorManager.unregisterListener(mLightSensorListener);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.close_btn:
                Intent intent = new Intent();
                if (Integer.valueOf(ProperTiesUtils.getProperties(mActivity, configfilename, "GSensorTest")) == 1) {
                    intent.putExtra("request", "GSensor");
                } else {
                    intent.putExtra("request", "LightSensor");
                }
                setResult(001, intent);
                finish();
                break;
            default:
                break;
        }
    }

    private void reStartActivity() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}
